<!DOCTYPE html>
<html lang="en">
<head>
    <title>WatchDog</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="./WTCHDGstatics/images/icons/favicon.ico" />

    <script src="./WTCHDGstatics/js/jquery-3.2.1.min.js"></script>
    <script src="./WTCHDGstatics/js/popper.min.js"></script>
    <link rel="stylesheet" type="text/css" href="./WTCHDGstatics/css/bootstrap.min.css" />
    <script src="./WTCHDGstatics/js/bootstrap.min.js"></script>
    <script src="./WTCHDGstatics/signalr/signalr.js"></script>
    <script src="./WTCHDGstatics/js/moment.min.js"></script>

    <style>
        body {
            color: #000;
            overflow-x: hidden;
            height: 100%;
            background-color: #EBEFFB;
            background-repeat: no-repeat;
            font-family: 'Avenir Next LT Pro', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body[data-theme="dark"] {
            --logo: url(./WTCHDGstatics/images/watchdogLogo.png) no-repeat;
        }

        fieldset {
            display: none
        }

        fieldset.show {
            display: block
        }

        select:focus,
        input:focus {
            -moz-box-shadow: none !important;
            -webkit-box-shadow: none !important;
            box-shadow: none !important;
            border: 1px solid #2196F3 !important;
            outline-width: 0 !important;
            font-weight: 400
        }

        button:focus {
            -moz-box-shadow: none !important;
            -webkit-box-shadow: none !important;
            box-shadow: none !important;
            outline-width: 0
        }

        .tabs {
            margin: 2px 5px 0px 5px;
            padding-bottom: 3px;
            cursor: pointer
        }

        .tabs:hover,
        .tabs.active {
            border-bottom: 1px solid #2196F3
        }

        a:hover {
            text-decoration: none;
            color: #1565C0
        }

        .box {
            margin-bottom: 10px;
            border-radius: 5px;
            padding: 10px
        }

        .modal-backdrop {
            background-color: #000000
        }

        .line {
            background-color: #CFD8DC;
            height: 1px;
            width: 100%
        }

        @media screen and (max-width: 768px) {
            .tabs h6 {
                font-size: 12px
            }
        }

        .dot {
            height: 12px;
            width: 12px;
            border-radius: 50%;
            display: inline-block;
        }

        pre {
            word-wrap: break-word;
            height: auto;
            max-height: 200px;
            overflow: auto
        }

        .logo{
            height:35px;
        }

        /*Skeleton Loader*/
        .skeleton {
            animation: skeleton-loading 1s linear infinite alternate;
        }

        @keyframes skeleton-loading {
            0% {
                background-color: hsl(200, 20%, 80%);
            }

            100% {
                background-color: hsl(200, 20%, 95%);
            }
        }

        .skeleton-text {
            width: 100%;
            height: 3.5rem;
            margin-bottom: 0.5rem;
            border-radius: 0.3rem;
        }
    </style>


</head>
<body>
    <section class="ftco-section pb-5">
        <div class="container">
            <div class="row d-flex float-right nav nav-tabs mx-1 mx-sm-3 mb-0 pb-0 border-0">
                <a data-toggle="tab" onclick="makeActive('reqLog', 'excptLog', 'inCodeLog')" href="#requestTab" style="color:black; text-decoration:none; text-underline-offset: 5px">
                    <div class="active">
                        <h6 id="reqLog" class="font-weight-bold">Request Logs</h6>
                    </div>
                </a>
                <a data-toggle="tab" onclick="makeActive('excptLog', 'reqLog', 'inCodeLog')" class="ml-3" href="#exceptionTab" style="color: black; text-decoration: none; text-underline-offset: 5px">
                    <div class="">
                        <h6 id="excptLog" class="font-weight-bold">Exception Logs</h6>
                    </div>
                </a>
                <a data-toggle="tab" onclick="makeActive('inCodeLog', 'reqLog', 'excptLog')" class="ml-3" href="#incodeTab" style="color: black; text-decoration: none; text-underline-offset: 5px">
                    <div class="">
                        <h6 id="inCodeLog" class="font-weight-bold">InCode Logs</h6>
                    </div>
                </a>
            </div>
            <div class="row mb-3 mb-3 mt-5 text-left">
                <img src="./WTCHDGstatics/images/watchdogLogo.png" class="logo" alt="Watchdog Logo" />
            </div>
            <div class="text-right">
                <button data-toggle="modal" data-target="#clearLogsModal" class="btn-sm btn btn-dark m-1 float-right">Clear Logs</button>
                <button onclick="logOut()" class="btn-sm btn btn-dark m-1 float-right">Log out</button>
            </div>


            <div class="tab-content">
                <div id="requestTab" class="tab-pane fade in active show">
                    <div class="mb-5 row">
                        <select id="myVerbDropDown" class="form-control col-md-1 m-1" aria-label="Default select HTTP Verb">
                            <option selected>ALL</option>
                            <option value="POST">POST</option>
                            <option value="GET">GET</option>
                            <option value="PUT">PUT</option>
                            <option value="PATCH">PATCH</option>
                            <option value="DELETE">DELETE</option>
                        </select>
                        <select id="myStatusCodeDropDown" class="form-control col-md-1 m-1" aria-label="Default select HTTP Verb">
                            <option selected>ALL</option>
                            <option value="200">200</option>
                            <option value="201">201</option>
                            <option value="301">301</option>
                            <option value="302">302</option>
                            <option value="400">400</option>
                            <option value="401">401</option>
                            <option value="404">404</option>
                            <option value="405">405</option>
                            <option value="407">407</option>
                            <option value="410">410</option>
                            <option value="415">415</option>
                            <option value="500">500</option>
                            <option value="503">503</option>
                        </select>
                        <input type="text" name="search" class="form-control col-md-2 m-1" id="searchString" />
                        <button onclick="search()" class="btn-sm btn btn-dark m-1">Search</button>
                        <a href="#" onclick="backToList(event)" class="m-1 mx-auto text-right col-md-6">Back to Full List</a>
                        <hr />

                    </div>
                    <div class="my-auto mb-5">
                        <b>Realtime Connection: <span id="dot" name="dot" class="dot" style="background-color: dodgerblue"></span></b>
                    </div>
                    <div class="mt-3 row">
                        <div class="col-md-12">
                            <div class="table">
                                <table class="table table-hover table-responsive-lg table-lg shadow p-3 mb-5 bg-light rounded">
                                    <thead class="thead-light">
                                        <tr>
                                            <th scope="col">Method</th>
                                            <th scope="col">Path</th>
                                            <th scope="col">Status Code</th>
                                            <th scope="col">Time Spent</th>
                                            <th scope="col">Time Stamp</th>
                                        </tr>
                                    </thead>
                                    <tbody id="tableBody">
                                    </tbody>
                                </table>
                            </div>
                            <div id="rqLoader">
                                <div class="skeleton skeleton-text"></div>
                                <div class="skeleton skeleton-text"></div>
                                <div class="skeleton skeleton-text"></div>
                                <div class="skeleton skeleton-text"></div>
                                <div class="skeleton skeleton-text"></div>
                                <div class="skeleton skeleton-text"></div>
                            </div>
                        </div>
                    </div>
                    <p class="lead text-center text-muted" id="pageMap"></p>
                    <div class="mb-5">
                        <button id="prev" class="text-left mr-5 btn-sm btn btn-dark float-left" onclick="prevPage()">Previous</button>
                        <button id="next" class="text-right ml-5 btn-sm btn btn-dark float-right" onclick="nextPage()">Next</button>
                    </div>
                </div>
                <div id="exceptionTab" class="tab-pane fade">
                    <div class="mb-5 row">
                        <input type="text" name="search" class="form-control col-md-2 m-1" id="exSearchString" />
                        <button onclick="exSearch()" class="btn-sm btn btn-dark m-1">Search</button>
                        <a href="#" onclick="backToList(event)" class="m-1 mx-auto text-right col-md-8">Back to Full List</a>
                        <hr />

                    </div>
                    <div class="my-auto mb-5">
                        <b>Realtime Connection: <span id="dot" name="dot" class="dot" style="background-color: dodgerblue"></span></b>
                    </div>
                    <div class="mt-3 row">
                        <div class="col-md-12">
                            <div class="table">
                                <table class="table table-hover table-responsive-lg table-lg shadow p-3 mb-5 bg-light rounded">
                                    <thead class="thead-light">
                                        <tr>
                                            <th scope="col">Source</th>
                                            <th scope="col">Message</th>
                                            <th scope="col">TypeOf</th>
                                            <th scope="col">Encountered At</th>
                                        </tr>
                                    </thead>
                                    <tbody id="tableBodyEx">
                                    </tbody>
                                </table>
                            </div>
                            <div id="exLoader">
                                <div class="skeleton skeleton-text"></div>
                                <div class="skeleton skeleton-text"></div>
                                <div class="skeleton skeleton-text"></div>
                                <div class="skeleton skeleton-text"></div>
                                <div class="skeleton skeleton-text"></div>
                                <div class="skeleton skeleton-text"></div>
                            </div>
                        </div>
                    </div>
                    <p class="lead text-center text-muted" id="exPageMap"></p>
                    <div class="mb-5">
                        <button id="exPrev" class="text-left mr-5 btn-sm btn btn-dark float-left" onclick="exPrevPage(event)">Previous</button>
                        <button id="exNext" class="text-right ml-5 btn-sm btn btn-dark float-right" onclick="exNextPage(event)">Next</button>
                    </div>
                </div>
                <div id="incodeTab" class="tab-pane fade">
                    <div class="mb-5 row">
                        <select id="myLogLevelDropDown" class="form-control col-md-2 m-1" aria-label="Default select Log Level">
                            <option selected>ALL</option>
                            <option value="Info">Info</option>
                            <option value="Warning">Warning</option>
                            <option value="Error">Error</option>
                        </select>
                        <input type="text" name="search" class="form-control col-md-2 m-1" id="inCodeSearchString" />
                        <button onclick="inCodeSearch()" class="btn-sm btn btn-dark m-1">Search</button>
                        <a href="#" onclick="backToList(event)" class="m-1 mx-auto text-right col-md-6">Back to Full List</a>
                        <hr />

                    </div>
                    <div class="my-auto mb-5">
                        <b>Realtime Connection: <span id="dot" name="dot" class="dot" style="background-color: dodgerblue"></span></b>
                    </div>
                    <div class="mt-3 row">
                        <div class="col-md-12">
                            <div class="table table-responsive">
                                <table class="table table-hover table-lg shadow p-3 mb-5 bg-light rounded">
                                    <thead class="thead-light">
                                        <tr>
                                            <th scope="col">Encountered At</th>
                                            <th scope="col">Origin</th>
                                            <th scope="col">Method</th>
                                            <th scope="col">LogLevel</th>
                                            <th scope="col">Message</th>
                                        </tr>
                                    </thead>
                                    <tbody id="tableBodyInCode">
                                    </tbody>
                                </table>
                            </div>
                            <div id="incodeLoader">
                                <div class="skeleton skeleton-text"></div>
                                <div class="skeleton skeleton-text"></div>
                                <div class="skeleton skeleton-text"></div>
                                <div class="skeleton skeleton-text"></div>
                                <div class="skeleton skeleton-text"></div>
                                <div class="skeleton skeleton-text"></div>
                            </div>
                        </div>
                    </div>
                    <p class="lead text-center text-muted" id="inCodePageMap"></p>
                    <div class="mb-5">
                        <button id="inCodePrev" class="text-left mr-5 btn-sm btn btn-dark float-left" onclick="inCodePrevPage(event)">Previous</button>
                        <button id="inCodeNext" class="text-right ml-5 btn-sm btn btn-dark float-right" onclick="inCodeNextPage(event)">Next</button>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-body p-5 shadow-lg">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h3 class="lead fa-underline">WatchLog</h3>
                    <div class="row">
                        <div class="col-md-12 m">
                            <p><b>Host: </b> <span id="host"></span></p>
                            <p style="word-wrap: break-word;"><b>Path: </b> <span id="path"></span></p>
                            <p style="word-wrap: break-word;"><b>Query: </b> <span id="query"></span></p>
                            <p><b>Method: </b> <span id="method"></span></p>
                            <p><b>IP Address: </b> <span id="ip"></span></p>
                            <p><b>Status Code: </b> <span id="statusCode"></span></p>
                            <p style="word-wrap: break-word;"><b>Time Spent: </b> <span id="time"></span></p>
                            <p style="word-wrap: break-word;"><b>Time Stamp: </b> <span id="startTime"></span></p>
                        </div>
                        <div class="col-md-12 purplebg m mt-3">


                            <div class="row d-flex justify-content-between mx-1 mx-sm-3 mb-0 pb-0 border-0">
                                <div class="tabs active" id="tab01">
                                    <h6 class="font-weight-bold">Request</h6>
                                </div>
                                <div class="tabs" id="tab02">
                                    <h6 class="text-muted">Response</h6>
                                </div>
                                <div class="tabs" id="tab03">
                                    <h6 class="text-muted">Headers</h6>
                                </div>
                            </div>
                            <div class="line mb-3"></div>

                            <div class="modal-body p-0">
                                <fieldset id="tab011" class="show">
                                    <div class="">
                                        <a href="#" id="reqBodyCopy" onclick="copyToClipboard(event, 'reqBody', 'reqBodyCopy')" style="display:none" class="float-right">Copy</a>
                                        <p class="lead">Request Body: </p>
                                        <pre id="reqBody" class="bg-light p-2"></pre>
                                    </div>
                                </fieldset>
                                <fieldset class="" id="tab021">
                                    <div class="">
                                        <a href="#" id="resBodyCopy" onclick="copyToClipboard(event, 'resBody', 'resBodyCopy')" style="display:none" class="float-right">Copy</a>
                                        <p class="lead">Response Body: </p>
                                        <pre id="resBody" class="bg-light p-2"></pre>
                                    </div>
                                </fieldset>
                                <fieldset id="tab031">
                                    <div class="">
                                        <p class="lead">Request Header: </p>
                                        <pre id="reqHd" class="bg-light p-2"></pre>
                                        <p class="lead mt-3">Response Header: </p>
                                        <pre id="resHd" class="bg-light p-2"></pre>
                                    </div>
                                </fieldset>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>

    <div class="modal" id="myExceptionModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-body p-5 shadow-lg">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h3 class="lead fa-underline">WatchLog Exceptions</h3>
                    <div class="">
                        <p style="word-wrap: break-word"><b>Message: </b> <span id="exMessage"></span></p>
                        <p style="word-wrap: break-word"><b>TypeOf: </b> <span id="exTypeOf"></span></p>
                        <p style="word-wrap: break-word"><b>Source: </b> <span id="exSource"></span></p>
                        <p style="word-wrap: break-word"><b>Method: </b> <span id="exMethod"></span></p>
                        <p style="word-wrap: break-word"><b>Path: </b> <span id="exPath"></span></p>
                        <p style="word-wrap: break-word"><b>Query: </b> <span id="exQuery"></span></p>
                        <p style="word-wrap: break-word"><b>Encountered At: </b> <span id="exTime"></span></p>
                    </div>
                    <div class="">
                        <a href="#" id="exStackTraceCopy" onclick="copyToClipboard(event, 'exStackTrace', 'exStackTraceCopy')" style="display:none" class="float-right">Copy</a>
                        <p class="lead"><b>Stack Trace:</b> </p>
                        <pre id="exStackTrace" class="bg-light p-2"></pre>

                        <a href="#" id="exReqBodyCopy" onclick="copyToClipboard(event, 'exReqBody', 'exReqBodyCopy')" style="display:none" class="float-right">Copy</a>
                        <p class="lead"><b>Request Body:</b> </p>
                        <pre id="exReqBody" class="bg-light p-2"></pre>
                    </div>

                </div>
            </div>
        </div>
    </div>

    <div class="modal" id="myInCodeModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-body p-5 shadow-lg">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h3 class="lead fa-underline mb-3">In-Code Log</h3>
                    <div class="">
                        <p style="word-wrap: break-word"><b>Event Id: </b> <span id="incodeEventId"></span></p>
                        <p style="word-wrap: break-word"><b>From File: </b> <span id="incodeFrom"></span></p>
                        <p style="word-wrap: break-word"><b>Method: </b> <span id="incodeMethod"></span></p>
                        <p style="word-wrap: break-word"><b>Line: </b> <span id="incodeLine"></span></p>
                        <p style="word-wrap: break-word"><b>Log Level: </b> <span id="incodeLogLevel"></span></p>
                        <p style="word-wrap: break-word"><b>Encountered At: </b> <span id="incodeTime"></span></p>
                    </div>
                    <div class="">
                        <a href="#" id="incodeMessageCopy" onclick="copyToClipboard(event, 'incodeMessage', 'incodeMessageCopy')" style="display:none" class="float-right">Copy</a>
                        <p class="lead"><b>Message:</b> </p>
                        <pre id="incodeMessage" class="bg-light p-2"></pre>
                    </div>

                </div>
            </div>
        </div>
    </div>

    <div class="modal" id="myLoginModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true" data-backdrop="static" data-keyboard="false">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-body p-5">
                    <h3 class="lead fa-underline mb-3">WatchDog Login</h3>
                    <div class="">
                        <form id="myLoginForm">
                            <input class="form-control m-1 mb-3" type="text" placeholder="Enter Username" name="uname" id="uname" required>
                            <input class="form-control m-1" type="password" placeholder="Enter Password" name="psw" id="psw" required>

                        </form>

                        <button class="btn btn-sm btn-dark m-1 mt-3" style="width:100%" onclick="login()" type="submit">Login</button>
                    </div>

                </div>
            </div>
        </div>
    </div>

    <div class="modal" id="clearLogsModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true" data-keyboard="false">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-body p-5 text-center">
                    <h3 class="lead fa-underline mb-3">Are you sure you want to clear all logs?</h3>
                    <div class="mx-auto text-center">
                        <a href="" onclick="clearLogs()" class="mr-5">Yes</a>
                        <a href="" data-dismiss="modal" class="ml-5">No</a>
                    </div>

                </div>
            </div>
        </div>
    </div>






    <script type="text/javascript">
        $(document).ready(function () {
            $(".tabs").click(function () {
                $(".tabs").removeClass("active");
                $(".tabs h6").removeClass("font-weight-bold");
                $(".tabs h6").addClass("text-muted");
                $(this).children("h6").removeClass("text-muted");
                $(this).children("h6").addClass("font-weight-bold");
                $(this).addClass("active");
                current_fs = $(".active");
                next_fs = $(this).attr('id');
                next_fs = "#" + next_fs + "1";
                $("fieldset").removeClass("show");
                $(next_fs).addClass("show");
                current_fs.animate({}, {
                    step: function () {
                        current_fs.css({
                            'display': 'none',
                            'position': 'relative'
                        });
                        next_fs.css({
                            'display': 'block'
                        });
                    }
                });
            });

            hasAuth().then(
                (data) => {
                    if (data === false) {
                        $('#myLoginModal').modal('show');
                    }
                })
        });

        var pageIndex = 1;
        var exPageIndex = 1;
        var inCodePageIndex = 1;
        document.getElementById('reqLog').style.textDecoration = "underline";
        var connection = new signalR.HubConnectionBuilder().withUrl("./wtchdlogger").build();

        connection.on("getLogs", function (data) {
            hasAuth().then(
                (authData) => {
                    if (authData === true) {
                        if (data.type === "rqLog") {
                            const firstDigitStr = String(data.log.responseStatus)[0];
                            var statusColor = firstDigitStr === '2' ? "text-success" : firstDigitStr === '1' || firstDigitStr === '3' ? "text-primary" : "text-danger";
                            const tr = $("<tr data-toggle='modal' data-target='#myModal' aria-expanded='false' aria-controls='collapse' class='collapsed'>" +
                                "<td><b>" + data.log.method + "</b></td><td>" + truncate(data.log.path, 50) + "</td><td><b class='" + statusColor + "'> " + data.log.responseStatus + "</b></td><td>" + data.log.timeSpent + "</td><td>" + moment(data.log.startTime).format('LLL') + "</td></tr>");
                            tr.on('click', populateModal.bind(null, data.log));
                            if (shouldShowOnFiltered(data.type, data.log)) {
                                $('#tableBody').prepend(tr);
                            }
                            
                        } else if (data.type === "exLog") {
                            const tr = $("<tr data-toggle='modal' data-target='#myExceptionModal' aria-expanded='false' aria-controls='collapse' class='collapsed'>" +
                                "<td><b>" + data.log.source + "</b></td><td>" + truncate(data.log.message, 50) + "</td><td>" + data.log.typeOf + "</td><td>" + moment(data.log.encounteredAt).format('LLL') + "</td></tr > ");
                            tr.on('click', populateExceptionModal.bind(null, data.log));
                            if (shouldShowOnFiltered(data.type, data.log)) {
                                $('#tableBodyEx').prepend(tr);
                            }
                        } else if (data.type === "log") {
                            const tr = $("<tr data-toggle='modal' data-target='#myInCodeModal' aria-expanded='false' aria-controls='collapse' class='collapsed'>" +
                                "<td><b>" + moment(data.log.timestamp).format('LLL') + "</b></td><td>" + (data.log.callingFrom ??= '') + "\nLine:" + data.log.lineNumber + "</td><td>" + (data.log.callingMethod ??= '') + "</td><td>" + data.log.logLevel + "</td><td>" + truncate(data.log.message, 50) + "</td></tr > ");
                            tr.on('click', populateInCodeModal.bind(null, data.log));
                            if (shouldShowOnFiltered(data.type, data.log)) {
                                $('#tableBodyInCode').prepend(tr);
                            }
                        }
                    }
                })
        });

        connection
            .start()
            .then(function () {
                $("[name='dot']").css("backgroundColor", "green");
                getLogs();
                getExceptionLogs();
                getInCodeLogs();
            }).catch(err => {
                getLogs();
                getExceptionLogs();
                getInCodeLogs();
                $("[name='dot']").css("backgroundColor", "red");
            });

        $("#myVerbDropDown").change(function (event) {
            $('#tableBody').empty();
            if ($("#myVerbDropDown")[0].selectedIndex === 0) {
                getLogs($('#searchString').val(), "", $('#myStatusCodeDropDown').val() == "ALL" ? "" : $('#myStatusCodeDropDown').val())
            } else {
                filterVerb($(this).val());
            }
        });

        $("#myStatusCodeDropDown").change(function (event) {
            $('#tableBody').empty();
            if ($("#myStatusCodeDropDown")[0].selectedIndex === 0) {
                getLogs($('#searchString').val(), $('#myVerbDropDown').val() == "ALL" ? "" : $('#myVerbDropDown').val(), "")
            } else {
                filterStatusCode($(this).val());
            }
        });
        $("#myLogLevelDropDown").change(function (event) {
            $('#tableBodyInCode').empty();
            if ($("#myLogLevelDropDown")[0].selectedIndex === 0) {
                getInCodeLogs($('#inCodeSearchString').val(), "")
            } else {
                filterLogLevel($(this).val());
            }
        });

        function shouldShowOnFiltered(logType, log) {
            shouldShow = true

            if (logType === "rqLog") {
                // check if searchString, verb and statusCode has a current value

                searchString = $('#searchString').val()
                statusCodeString = $('#myStatusCodeDropDown').val()
                verbString = $('#myVerbDropDown').val()

                if (!searchString && statusCodeString === "ALL" && verbString === "ALL") {
                    return true;
                }

                searchString = searchString.toLowerCase();

                if (searchString && (log.path?.toLowerCase().includes(searchString) || log.method?.toLowerCase().includes(searchString) ||
                    (log.queryString && log.queryString?.toLowerCase().includes(searchString)))) {

                    shouldShow &= true;

                }

                if (verbString !== "ALL") {
                    if (log.method?.toLowerCase() !== verbString.toLowerCase()) {
                        shouldShow &= false
                    }
                }

                if (statusCodeString !== "ALL") {
                    if (log.responseStatus != statusCodeString) {
                        shouldShow &= false
                    }
                }


            } else if (logType === "exLog") {

               // check if searchString has a current value

                searchString = $('#exSearchString').val()

                if (!searchString) {
                    return true;
                }

                searchString = searchString.toLowerCase()
                if (log.message.toLowerCase().includes(searchString) || log.stackTrace.includes(searchString) || log.source.includes(searchString)) {
                    return true;
                }

            } else if (logType === "log") {

                 // check if searchString and logLevelString has a current value

                searchString = $('#inCodeSearchString').val()
                logLevelString = $('#myLogLevelDropDown').val()

                if (!searchString && logLevelString === "ALL") {
                    return true;
                }

                searchString = searchString.toLowerCase();
                logLevelString = logLevelString.toLowerCase();

                if ((searchString && (log.message.toLowerCase().includes(searchString) || log.callingMethod.toLowerCase().includes(searchString) ||
                    log.callingFrom.toLowerCase().includes(searchString) ||
                    (log.eventId && log.eventId.toLowerCase().includes(searchString)))) && (logLevelString !== "ALL" && log.logLevel.toLowerCase() === logLevelString))
                {
                    return true;
                }

            }

            return shouldShow
        }

        function getLogs(searchString = "", verb = "", statusCode = "") {
            $('#rqLoader').show();
            $.ajax({
                type: "GET",
                url: "./WTCHDwatchpage?pageNumber=" + pageIndex + "&searchString=" + searchString + "&verbString=" + verb + "&statusCode=" + statusCode,
                context: document.body,
                success: function (data) {
                    var totalPages = data.totalPages === 0 ? 1 : data.totalPages
                    $('#pageMap').text("Page " + data.pageIndex + " of " + totalPages);
                    if (data.hasNext === false) {
                        $('#next').hide();
                    }
                    else {
                        $('#next').show();
                    }

                    if (data.hasPrevious === false) {
                        $('#prev').hide();
                    }
                    else {
                        $('#prev').show();
                    }

                    $('#rqLoader').hide();

                    for (var i = 0; i < data.logs.length; i++) {
                        const firstDigitStr = String(data.logs[i].responseStatus)[0];
                        var statusColor = firstDigitStr === '2' ? "text-success" : firstDigitStr === '1' || firstDigitStr === '3' ? "text-primary" : "text-danger";
                        const tr = $("<tr data-toggle='modal' data-target='#myModal' aria-expanded='false' aria-controls='collapse" + i + "' class='collapsed'>" +
                            "<td><b>" + data.logs[i].method + "</b></td><td>" + truncate(data.logs[i].path, 50) + "</td><td><b class='" + statusColor + "'> " + data.logs[i].responseStatus + "</b ></td ><td>" + data.logs[i].timeSpent + "</td><td>" + moment(data.logs[i].startTime).format('LLL') + "</td></tr > ");
                        tr.on('click', populateModal.bind(null, data.logs[i]));
                        $('#tableBody').append(tr);
                    }
                },
                error: function (error) {
                    $('#rqLoader').hide();
                    if (error.status === 401) {
                        $('#myLoginModal').modal('show');
                    }
                }
            });
        }

        function getExceptionLogs(searchString = "") {
            $('#exLoader').show();
            $.ajax({
                type: "GET",
                url: "./WTCHDwatchpage/Exceptions?pageNumber=" + exPageIndex + "&searchString=" + searchString,
                context: document.body,
                success: function (data) {
                    var totalPages = data.totalPages === 0 ? 1 : data.totalPages
                    $('#exPageMap').text("Page " + data.pageIndex + " of " + totalPages);
                    if (data.hasNext === false) {
                        $('#exNext').hide();
                    }
                    else {
                        $('#exNext').show();

                    }

                    if (data.hasPrevious === false) {
                        $('#exPrev').hide();
                    }
                    else {
                        $('#exPrev').show();
                    }

                    $('#exLoader').hide();

                    for (var i = 0; i < data.logs.length; i++) {
                        const tr = $("<tr data-toggle='modal' data-target='#myExceptionModal' aria-expanded='false' aria-controls='collapse" + i + "' class='collapsed'>" +
                            "<td><b>" + data.logs[i].source + "</b></td><td>" + truncate(data.logs[i].message, 50) + "</td><td>" + data.logs[i].typeOf + "</td><td>" + moment(data.logs[i].encounteredAt).format('LLL') + "</td></tr > ");
                        tr.on('click', populateExceptionModal.bind(null, data.logs[i]));
                        $('#tableBodyEx').append(tr);
                    }
                },
                error: function (error) {
                    $('#exLoader').hide();
                    if (error.status === 401) {
                        $('#myLoginModal').modal('show');
                    }
                }
            });
        }
        function getInCodeLogs(searchString = "", logLevelString = "") {
            $('#incodeLoader').show();
            $.ajax({
                type: "GET",
                url: "./WTCHDwatchpage/Logs?pageNumber=" + inCodePageIndex + "&searchString=" + searchString + "&logLevelString=" + logLevelString,
                context: document.body,
                success: function (data) {
                    var totalPages = data.totalPages === 0 ? 1 : data.totalPages
                    $('#inCodePageMap').text("Page " + data.pageIndex + " of " + totalPages);
                    if (data.hasNext === false) {
                        $('#inCodeNext').hide();
                    }
                    else {
                        $('#inCodeNext').show();

                    }

                    if (data.hasPrevious === false) {
                        $('#inCodePrev').hide();
                    }
                    else {
                        $('#inCodePrev').show();
                    }

                    $('#incodeLoader').hide();

                    for (var i = 0; i < data.logs.length; i++) {
                        const tr = $("<tr data-toggle='modal' data-target='#myInCodeModal' aria-expanded='false' aria-controls='collapse" + i + "' class='collapsed'>" +
                            "<td><b>" + moment(data.logs[i].timestamp).format('LLL') + "</b></td><td>" + (data.logs[i].callingFrom ??= '') + "\nLine:" + data.logs[i].lineNumber + "</td><td>" + (data.logs[i].callingMethod ??= '') + "</td><td>" + data.logs[i].logLevel + "</td><td>" + truncate(data.logs[i].message, 50) + "</td></tr > ");
                        tr.on('click', populateInCodeModal.bind(null, data.logs[i]));
                        $('#tableBodyInCode').append(tr);
                    }
                },
                error: function (error) {
                    $('#incodeLoader').hide();
                    if (error.status === 401) {
                        $('#myLoginModal').modal('show');
                    }
                }
            });
        }


        function clearLogs() {
            $.ajax({
                type: "POST",
                url: "./WTCHDwatchpage/ClearLogs",
                success: function (data) {
                    window.location.reload()
                },
                error: function (error) {
                    if (error.status === 401) {
                        $('#myLoginModal').modal('show');
                    }
                }
            });
        }

        function search() {
            pageIndex = 1;
            $('#tableBody').empty();
            var ss = $('#searchString').val();
            getLogs(ss, $('#myVerbDropDown').val() == "ALL" ? "" : $('#myVerbDropDown').val(), $('#myStatusCodeDropDown').val() == "ALL" ? "" : $('#myStatusCodeDropDown').val());
        }

        function exSearch() {
            $('#tableBodyEx').empty();
            exPageIndex = 1;
            var ss = $('#exSearchString').val();
            getExceptionLogs(ss, $('#myLogLevelDropDown').val() == "ALL" ? "" : $('#myLogLevelDropDown').val());
        }

        function inCodeSearch() {
            $('#tableBodyInCode').empty();
            inCodePageIndex = 1;
            var ss = $('#inCodeSearchString').val();
            getInCodeLogs(ss);
        }

        function filterVerb(verbString) {
            pageIndex = 1;
            $('#tableBody').empty();
            getLogs($('#searchString').val(), verbString, $('#myStatusCodeDropDown').val() == "ALL" ? "" : $('#myStatusCodeDropDown').val());
        }

        function filterStatusCode(statusCodeString) {
            pageIndex = 1;
            $('#tableBody').empty();
            getLogs($('#searchString').val(), $('#myVerbDropDown').val() == "ALL" ? "" : $('#myVerbDropDown').val(), statusCodeString);
        }

        function filterLogLevel(logLevelString) {
            inCodePageIndex = 1;
            $('#tableBodyInCode').empty();
            getInCodeLogs($('#inCodeSearchString').val(), logLevelString);
        }

        function nextPage() {
            ++pageIndex;
            $('#tableBody').empty();
            getLogs($('#searchString').val(), $('#myVerbDropDown').val() == "ALL" ? "" : $('#myVerbDropDown').val(), $('#myStatusCodeDropDown').val() == "ALL" ? "" : $('#myStatusCodeDropDown').val());
        }

        function prevPage() {
            if (pageIndex > 1)
                --pageIndex;
            $('#tableBody').empty();
            getLogs($('#searchString').val(), $('#myVerbDropDown').val() == "ALL" ? "" : $('#myVerbDropDown').val(), $('#myStatusCodeDropDown').val() == "ALL" ? "" : $('#myStatusCodeDropDown').val());
        }

        function exNextPage(e) {
            ++exPageIndex;
            $('#tableBodyEx').empty();
            getExceptionLogs($('#searchString').val());
        }

        function exPrevPage(e) {
            if (exPageIndex > 1)
                --exPageIndex;
            $('#tableBodyEx').empty();
            getExceptionLogs($('#searchString').val());
        }

        function inCodeNextPage(e) {
            ++inCodePageIndex;
            $('#tableBodyInCode').empty();
            getInCodeLogs($('#searchString').val());
        }

        function inCodePrevPage(e) {
            if (inCodePageIndex > 1)
                --inCodePageIndex;
            $('#tableBodyInCode').empty();
            getInCodeLogs($('#searchString').val());
        }

        function backToList(e) {
            pageIndex = 1;
            inCodePageIndex = 1;
            exPageIndex = 1;
            $('#tableBody').empty();
            $('#tableBodyEx').empty();
            $('#tableBodyInCode').empty();
            getLogs();
            getExceptionLogs();
            getInCodeLogs();

            $('#searchString').val("");
            $('#exSearchString').val("");
            $('#inCodeSearchString').val("");
            $('#myVerbDropDown').val("ALL");
            $('#myStatusCodeDropDown').val("ALL");
            $('#myLogLevelDropDown').val("ALL");

            e = e || window.event;
            e.preventDefault();
        }

        function logOut() {
            $.ajax({
                type: "GET",
                url: "./WTCHDwatchpage/LogOut",
                success: function (data) {
                    window.location.reload()
                }
            });
        }

        function login() {
            var form = document.querySelector('form')
            form.reportValidity()
            if (form.checkValidity()) {
                $.ajax({
                    type: "POST",
                    url: "./WTCHDwatchpage/Auth",
                    data: {
                        username: $("#uname").val(),
                        password: $("#psw").val()
                    },
                    context: document.body,
                    success: function (data) {

                        window.location.reload()
                    }
                });
            }

        }

        function hasAuth() {
            return new Promise(function (resolve, reject) {
                $.ajax({
                    type: "GET",
                    url: "./WTCHDwatchpage/IsAuth",
                    success: function (data) {
                        resolve(data) // Resolve promise and when success
                    },
                    error: function (err) {
                        reject(err) // Reject the promise and go to catch()
                    }
                });
            });
        }

       

        function populateModal(data) {
            $('#host').text(data.host);
            $('#path').text(data.path);
            $('#query').text(data.queryString);
            $('#method').text(data.method);
            $('#ip').text(data.ipAddress);
            $('#statusCode').text(data.responseStatus);
            $('#time').text(data.timeSpent);
            $('#startTime').text(moment(data.startTime).format('LLL'));

            $('#reqHd').text(data.requestHeaders);
            $('#resHd').text(data.responseHeaders);
            $('#reqBody').text(data.requestBody);

            $('#resBody').text(data.responseBody);


            if (data.responseBody != null && data.responseBody !== "") {
                document.getElementById("resBodyCopy").style.display = "block";
                var element = document.getElementById("resBody");
                if (data.responseBody.includes("{")) {
                    var obj = JSON.parse(element.innerText);
                    element.innerHTML = JSON.stringify(obj, undefined, 2);
                }
            } else {
                document.getElementById("resBodyCopy").style.display = "none";
            }
            if (data.requestBody != null && data.requestBody !== "") {
                document.getElementById("reqBodyCopy").style.display = "block";
                var element2 = document.getElementById("reqBody");
                if (data.requestBody.includes("{")) {
                    var obj2 = JSON.parse(element2.innerText);
                    element2.innerHTML = JSON.stringify(obj2, undefined, 2);
                }
            } else {
                document.getElementById("reqBodyCopy").style.display = "none";
            }
        }

        function populateExceptionModal(data) {
            $('#exMessage').text(data.message);
            $('#exTypeOf').text(data.typeOf);
            $('#exSource').text(data.source);
            $('#exTime').text(moment(data.encounteredAt).format('LLL'));
            $('#exStackTrace').text(data.stackTrace);
            $('#exReqBody').text(data.requestBody);
            $('#exPath').text(data.path);
            $('#exMethod').text(data.method);
            $('#exQuery').text(data.queryString);

            if (data.stackTrace != null && data.stackTrace !== "") {
                document.getElementById("exStackTraceCopy").style.display = "block";
                var element = document.getElementById("exStackTrace");
                if (data.stackTrace.includes("{")) {
                    var obj = JSON.parse(element.innerText);
                    element.innerHTML = JSON.stringify(obj, undefined, 2);
                }
            } else {
                document.getElementById("exReqBodyCopy").style.display = "none";
            }
            if (data.requestBody != null && data.requestBody !== "") {
                document.getElementById("exReqBodyCopy").style.display = "block";
                var element2 = document.getElementById("exReqBody");
                if (data.requestBody.includes("{")) {
                    var obj2 = JSON.parse(element2.innerText);
                    element2.innerHTML = JSON.stringify(obj2, undefined, 2);
                }
            } else {
                document.getElementById("exReqBodyCopy").style.display = "none";
            }
        }

        function populateInCodeModal(data) {
            $('#incodeFrom').text(data.callingFrom);
            $('#incodeLine').text(data.lineNumber);
            $('#incodeMethod').text(data.callingMethod);
            $('#incodeTime').text(moment(data.timestamp).format('LLL'));
            $('#incodeLogLevel').text(data.logLevel);
            $('#incodeMessage').text(data.message);
            $('#incodeEventId').text(data.eventId);

            if (data.message != null && data.message !== "") {
                document.getElementById("incodeMessageCopy").style.display = "block";
            } else {
                document.getElementById("incodeMessageCopy").style.display = "none";
            }
        }

        function sleep(time) {
            return new Promise((resolve) => setTimeout(resolve, time));
        }

        function copyToClipboard(e, id, tag) {
            var copyText = document.getElementById(id).innerHTML;
            navigator.clipboard.writeText(copyText);

            /* Alert the copied text */
            document.getElementById(tag).innerHTML = "Copied!";

            sleep(1500).then(() => {
                document.getElementById(tag).innerHTML = "Copy";
            });
            e = e || window.event;
            e.preventDefault();
        }

        function makeActive(id, removeId, removeNextId) {
            document.getElementById(id).style.textDecoration = "underline";
            document.getElementById(removeId).style.textDecoration = "none";
            document.getElementById(removeNextId).style.textDecoration = "none";
        }

        function truncate(str, num) {
            if (str.length > num) {
                return str.slice(0, num) + "...";
            } else {
                return str;
            }
        }
    </script>

</body>
</html>
